import Database from 'better-sqlite3';
import path from 'path';

const DB_PATH = path.join(process.cwd(), 'data', 'delivery-management.db');
const db = new Database(DB_PATH);

function updateRolePermissions() {
  console.log('🔄 更新角色权限配置...');

  // 更新管理员权限
  const updateAdminStmt = db.prepare(`
    UPDATE roles SET permissions = ? WHERE code = 'A'
  `);
  updateAdminStmt.run(JSON.stringify({
    canEditAll: true,
    canManageUsers: true,
    canManageRoles: true,
    dataSourceAccess: ['P', 'E', 'M', 'O', 'C', 'R']
  }));

  // 更新采购人员权限
  const updateProcurementStmt = db.prepare(`
    UPDATE roles SET permissions = ? WHERE code = 'P'
  `);
  updateProcurementStmt.run(JSON.stringify({
    canEditAll: false,
    canManageUsers: false,
    canManageRoles: false,
    dataSourceAccess: ['P'],
    editableFields: {
      // 基于实际字段名称
      table_c2: ['采购物资编码', '采购包号批次', '制造出厂编码', '物流编码', '仓储编码', '石油天然气行业设备编码'],
      table_c4: ['采购批次', '供应商信息'],
      table_c18: ['制造厂家', '供货厂家', '型号', '规格', '额定功率', '额定电流', '额定转速', '装箱单号']
    }
  }));

  // 更新设计人员权限
  const updateDesignStmt = db.prepare(`
    UPDATE roles SET permissions = ? WHERE code = 'E'
  `);
  updateDesignStmt.run(JSON.stringify({
    canEditAll: false,
    canManageUsers: false,
    canManageRoles: false,
    dataSourceAccess: ['E'],
    editableFields: {
      table_c2: ['设计物资编码', '流水码'],
      table_c4: ['安装位置', '系统分区', '楼层信息'],
      table_c18: ['设备名称', '功能描述']
    }
  }));

  // 更新监测人员权限 (M数据源)
  const updateMonitoringStmt = db.prepare(`
    UPDATE roles SET permissions = ? WHERE code = 'M'
  `);
  updateMonitoringStmt.run(JSON.stringify({
    canEditAll: false,
    canManageUsers: false,
    canManageRoles: false,
    dataSourceAccess: ['M'],
    editableFields: {
      table_c2: ['监测点编号', '监测设备编号'],
      table_c4: ['监测位置', '监测点位'],
      table_c18: ['监测数据', '监测记录', '状态参数']
    }
  }));

  // 更新施工人员权限
  const updateConstructionStmt = db.prepare(`
    UPDATE roles SET permissions = ? WHERE code = 'C'
  `);
  updateConstructionStmt.run(JSON.stringify({
    canEditAll: false,
    canManageUsers: false,
    canManageRoles: false,
    dataSourceAccess: ['C'],
    editableFields: {
      table_c2: ['施工物资编码', '施工自编号'],
      table_c4: ['施工位置', '施工进度'],
      table_c18: ['施工状态', '安装日期']
    }
  }));

  // 更新建设人员权限
  const updateBuildStmt = db.prepare(`
    UPDATE roles SET permissions = ? WHERE code = 'O'
  `);
  updateBuildStmt.run(JSON.stringify({
    canEditAll: false,
    canManageUsers: false,
    canManageRoles: false,
    dataSourceAccess: ['O'],
    editableFields: {
      table_c2: ['建设编号', '验收编号'],
      table_c4: ['建设位置', '调试位置'],
      table_c18: ['建设状态', '调试参数', '验收数据']
    }
  }));

  // 更新运维人员权限 (R数据源)
  const updateOperationsStmt = db.prepare(`
    UPDATE roles SET permissions = ? WHERE code = 'R'
  `);
  updateOperationsStmt.run(JSON.stringify({
    canEditAll: false,
    canManageUsers: false,
    canManageRoles: false,
    dataSourceAccess: ['R'],
    editableFields: {
      table_c2: ['运行资产编码', '运行自编号'],
      table_c4: ['当前位置', '运维责任人'],
      table_c18: ['运行状态', '维护记录', '运维编号']
    }
  }));

  // 更新查看人员权限
  const updateViewerStmt = db.prepare(`
    UPDATE roles SET permissions = ? WHERE code = 'V'
  `);
  updateViewerStmt.run(JSON.stringify({
    canEditAll: false,
    canManageUsers: false,
    canManageRoles: false,
    dataSourceAccess: ['P', 'E', 'M', 'O', 'C', 'R'],
    editableFields: {}
  }));

  console.log('✅ 角色权限更新完成');
}


function showUpdatedRoles() {
  console.log('\n📋 更新后的角色权限:');
  
  const getRolesStmt = db.prepare('SELECT * FROM roles ORDER BY name');
  const roles = getRolesStmt.all() as any[];

  roles.forEach(role => {
    const permissions = JSON.parse(role.permissions);
    console.log(`\n🔐 ${role.name} (${role.code}):`);
    console.log(`   数据来源: ${permissions.dataSourceAccess.join(', ')}`);
    if (permissions.editableFields && Object.keys(permissions.editableFields).length > 0) {
      console.log(`   可编辑字段:`);
      Object.entries(permissions.editableFields).forEach(([table, fields]: [string, any]) => {
        console.log(`     ${table}: ${fields.join(', ')}`);
      });
    }
  });
}

async function main() {
  try {
    updateRolePermissions();
    showUpdatedRoles();

    console.log('\n🎉 角色权限系统更新完成!');
    console.log('\n📋 测试账号信息 (数据源分类已更新):');
    console.log('┌─────────────┬──────────┬─────────────┬──────────────┬─────────────────┐');
    console.log('│ 用户名      │ 密码     │ 角色        │ 数据来源     │ 说明            │');
    console.log('├─────────────┼──────────┼─────────────┼──────────────┼─────────────────┤');
    console.log('│ admin       │ admin123 │ 系统管理员  │ P,E,M,O,C,R  │ 所有权限        │');
    console.log('│ procurement │ proc123  │ 采购人员    │ P            │ 采购数据        │');
    console.log('│ design      │ design123│ 设计人员    │ E            │ 设计数据        │');
    console.log('│ monitoring  │ mon123   │ 监测人员    │ M            │ 监测数据        │');
    console.log('│ construction│ const123 │ 施工人员    │ C            │ 施工数据        │');
    console.log('│ build       │ build123 │ 建设人员    │ O            │ 建设调试数据    │');
    console.log('│ operations  │ ops123   │ 运维人员    │ R            │ 运维操作数据    │');
    console.log('│ viewer      │ view123  │ 查看人员    │ P,E,M,O,C,R  │ 只读权限        │');
    console.log('└─────────────┴──────────┴─────────────┴──────────────┴─────────────────┘');
    console.log('\n✨ 数据源说明:');
    console.log('  E = 设计数据 (Design)');
    console.log('  M = 监测数据 (Monitoring)');
    console.log('  R = 运维数据 (Operations)');
    console.log('  P = 采购数据 (Procurement)');
    console.log('  C = 施工数据 (Construction)');
    console.log('  O = 建设数据 (Build)');

  } catch (error) {
    console.error('❌ 更新角色权限失败:', error);
    process.exit(1);
  } finally {
    db.close();
  }
}

main();
